/*******************************************************************************
 * Copyright (c) 2014 Francesco Gabbrielli.
 * 
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v2.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * 
 * Contributors:
 *     Francesco Gabbrielli - initial API and implementation
 ******************************************************************************/
package it.francescogabbrielli.android.solidalapp;

import it.francescogabbrielli.android.solidalapp.SolidalApp.DataKey;
import it.francescogabbrielli.android.solidalapp.requestendpoint.model.Request;
import it.francescogabbrielli.android.solidalapp.responseendpoint.model.Response;

import com.google.android.gms.gcm.GoogleCloudMessaging;

import android.app.IntentService;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;

public class GCMService extends IntentService {
	
	private static final String PROJECT_NUMBER = "110637436951";
	
	private static final String TAG = SolidalApp.TAG + " GCM";
	
	public GCMService() {
		super("GCM Service");
	}
	
	@Override
	protected void onHandleIntent(Intent intent) {
		
		Intent localIntent = new Intent();
		
		SolidalApp app = (SolidalApp) getApplicationContext();
		
		try {
			
			switch(IntentAction.valueOf(intent)) {
			
			case GCM_REGISTER_DEVICE:
				try {
					SharedPreferences prefs = getSharedPreferences(SolidalApp.class.getCanonicalName(), MODE_PRIVATE);
					SharedPreferences.Editor edit = prefs.edit();
					String id = GoogleCloudMessaging.getInstance(this).register(PROJECT_NUMBER);
					Log.d(TAG, "Registered to GCM: "+id);
					edit.putString(Constants.REGISTRATION_ID, id);
					edit.commit();
					localIntent.putExtra(Constants.REGISTRATION_ID, id);
				} catch(Exception e) {
					localIntent.putExtra("error", e.toString());
					Log.e(TAG, "Error registering to GCM", e);
				}
				break;
								
			default:
			}
			
		} catch(Exception e) {
			Log.e(TAG, "Unexpected error", e);
		}

		localIntent.setAction(intent.getAction());
		Log.v(TAG, "broadcasting: "+localIntent+"\n"+localIntent.getExtras());
		sendBroadcast(localIntent);
//		try {
//			PendingIntent receiver = intent.getParcelableExtra(Constants.RECEIVER);
//			receiver.send(this, 0, localIntent);
//			Log.v(TAG, "broadcasting: "+localIntent+"\n"+localIntent.getExtras());
//		} catch(Exception e) {
//			Log.e(TAG, "Cannot broadcast: "+localIntent+"\n"+localIntent.getExtras(), e);
//		}
		
	}
	
}
